<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserModel
 *
 * @author julien
 */
require_once 'Classes/Model/PDOModel.php';
require_once 'Classes/User.php';
class UserModel extends PDOModel implements Singleton {
    
     private static $instance;
     
     public function getInstance(){
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
     }
     
     public function __clone() {
         throw new Exception("You may not try to clone this object");
     }
 
    
    protected function __construct() {
        parent::__construct();
        
    }
    
    
    
   
    
    private function selectUserFromBDD($column,$value){
        
        return $this->PDORequest('SELECT * FROM '.$this->table['users'].' WHERE '.$column.'=?',array($value));
    }
    
     private function deleteUserFromBDD($column,$value){
        
        return $this->PDORequest('DELETE FROM '.$this->table['users'].' WHERE '.$column.'=?',array($value));
    }
    
    
    public function getUserByUsername($username){
       
        $dbData = $this->selectUserFromBDD('UserName', $username);
        return new User($dbData[0]);
    }
    
    public function getUserById($id){
        
        $dbData = $this->selectUserFromBDD('ID', $id);
        return new User($dbData[0]);
    }
    
    
    public function addUser($user){
        $sql='INSERT INTO '.$this->table['users'].' (UserName, Password, Role) VALUES(?,?,?)';
        $data = array($user->getUsername(), $user->getPassword(), $user->getRole());
        $this->PDORequest($sql,$data);
    }
    
    public function updateUser($user){
        $sql='UPDATE '.$this->table['users'].' SET UserName=?,Password=?,Role=? WHERE ID=?';
        $data = array($user->getUsername(), $user->getPassword(), $user->getRole(),$user->getId());
        $this->PDORequest($sql,$data);
    }
    
    public function deleteUser($user){
        $this->deleteUserById($user->getId());
    }
    
    public function deleteUserById($id){
        $this->deleteUserFromBDD('ID', $id);
    }
    
    public function deleteUserByUsername($username){
         $this->deleteUserFromBDD('UserName', $username);
    }
}

?>
